﻿using System;
using System.IO;
using System.Text.RegularExpressions;

using UnityEngine;
using Util;
using XLua;

public class LuaFileMgr
{
    //编辑器代码位置
    public const string LUA_MAIN_PATHB = "Assets/Scripts/Logic/Lua";

    public const string LUA_MAIN_PATH = LUA_MAIN_PATHB + "/";

    //缓存加载代码位置
    public static string LUA_Txt_MAIN_PATHB = Application.persistentDataPath + "/Lua";

    public static string LUA_Txt_MAIN_PATH_TL = Application.persistentDataPath + "/Lua/ThermalLoading.ld";
    public static string LUA_Txt_MAIN_PATH = LUA_Txt_MAIN_PATHB + "/";

    public const string LUA_TYPE = ".lua";
    public const string LUA_DTAT_TYPE = ".ld";

    //创建缓存
    public static void CreateAndUpdate(string path)
    {
        var npath = LUA_Txt_MAIN_PATH + path.Remove(0, LUA_MAIN_PATH.Length);
        var name = npath.Split('/').toEnd();
        var finpath = npath.Remove(npath.Length - name.Length, name.Length);
        var zname = name.Split('.').toStr();
        var fname = zname + LUA_DTAT_TYPE;

        var epath = PathConfig.Project + "/" + LUA_MAIN_PATHB + "/";
        var com = FileIO.Load(epath, name).ToString();

        debug.log("Amend : " + name);
        FileIO.SaveByte(finpath, fname, com);

        var luaName = name.Split('.').toStr();

        UdpSend(luaName, com);
    }

    public static void UdpSend(string name, string com)
    {
        string Data = name + "&&&" + com;
        NetUdp.Instance.SendMessage(Data);
#if UNITY_EDITOR //编辑器环境下要重写真实文件路径的文件
        if (Application.isPlaying)
        {
            UdpReceive(Data);
        }
#endif
    }

    public static void UdpReceive(string com)
    {
        string[] sArray = Regex.Split(com, "&&&", RegexOptions.IgnoreCase);
        var luaName = sArray[0];

#if !UNITY_EDITOR //不是编辑器环境下要重写真实文件路径的文件
        var fname = luaName + LUA_DTAT_TYPE;
        var Com = sArray[1];
        var finpath = LUA_Txt_MAIN_PATH;
        FileIO.SaveByte(finpath, fname, Com);
#endif
        debug.log("Reload : " + luaName);
        //如果有监听肯定是运行了
        XLuaMgr.Instance.ReloadModule(luaName);

        LuaTable newLua = XLuaMgr.Instance.luaenv.Global.Get<LuaTable>("newLua");//映射到LuaTable，by ref
        newLua.Get<Action>("FastShowTip").Invoke();
    }

    //删除缓存
    public static void Delete(string path)
    {
        var npath = LUA_Txt_MAIN_PATH + path.Remove(0, LUA_MAIN_PATH.Length);
        var name = npath.Split('/').toEnd();
        var finpath = npath.Remove(npath.Length - name.Length, name.Length);
        var fname = name.Split('.').toStr() + LUA_DTAT_TYPE;
        string cpaht = finpath + fname;
        debug.log("Delete : " + cpaht);
        FileIO.Delete(cpaht);
    }

    //加载Lua文件
    public static byte[] Read(string name)
    {
        var path = LUA_Txt_MAIN_PATH;
        var names = name + LUA_DTAT_TYPE;
        //Debug.Log("Read : " + path + names);
        var com = FileIO.LoadByte(path, names);
        return com;
    }

    //将代码全部编入缓存
    private static void FileTraversal(string filePath)
    {
        //判断当前路径所指向的是否为文件
        if (File.Exists(filePath) == false)
        {
            string[] str1 = Directory.GetFileSystemEntries(filePath);
            foreach (string s1 in str1)
            {
                FileTraversal(s1);
            }
        }
        else
        {
            bool isLuaFile = filePath.EndsWith(LUA_TYPE);
            if (isLuaFile)
            {
                var paht = filePath.Remove(0, PathConfig.Project.Length + 1).Replace("\\", "/");
                CreateAndUpdate(paht);
            }
        }
    }

    public static void JoinCache()
    {
        var pathbase = PathConfig.Project + "/" + LuaFileMgr.LUA_MAIN_PATHB;
        FileTraversal(pathbase);
    }

    //查询缓存
    public static void ExamineCache()
    {
        if (!IsExamineCache())
        {
            JoinCache();
        }
    }

    //查询缓存
    public static bool IsExamineCache()
    {
        if (FileIO.isLoadPath(LUA_Txt_MAIN_PATH_TL))
        {
            return true;
        }
        return false;
    }

    // [MenuItem("Tools/Lua/CreationPack")]
    // public static void CreationPack()
    // {
    //     var pathIn = PathConfig.Project + "/Assets/Scripts/Logic/Lua";
    //     var pathOut = PathConfig.Project + "/LuaPack/LUA_MAIN.zip";
    //     Util.ZipUtility.ZipCallback _zipCallback = new ZipUtility.ZipCallbacks((z) =>
    //     {
    //         debug.log("压缩完成");
    //     });
    //
    //     debug.log(pathIn, pathOut);
    //     if (FileIO.isLoadPath(pathOut))
    //     {
    //         FileIO.Delete(pathOut);
    //     }
    //     FileIO.CreateSavePath(PathConfig.Project + "/LuaPack/");
    //     ZipUtility.Zip(pathIn, pathOut, null, _zipCallback);
    // }
    //
    // [MenuItem("Tools/Lua/UnPack")]
    // public static void UnPack()
    // {
    //     var pathIn = PathConfig.Project + "/LuaPack/LUA_MAIN.zip";
    //     var pathOut = PathConfig.Project + "/LuaPack";
    //     Util.ZipUtility.UnzipCallbacks _zipCallback = new ZipUtility.UnzipCallbacks();
    //     _zipCallback.backs = (_) =>
    //     {
    //         debug.log("解压完成");
    //         FileIO.Delete(pathIn);
    //     };
    //     _zipCallback.postBacks = (e) =>
    //     {
    //         debug.log(e.Name);
    //     };
    //
    //     FileIO.CreateSavePath(pathOut);
    //     debug.log(pathIn, pathOut);
    //     ZipUtility.UnzipFile(pathIn, pathOut, null, _zipCallback);
    // }
}